// 网络拓扑分析页面功能
class TopologyPage {
    constructor() {
        this.svg = null;
        this.width = 800;
        this.height = 600;
        this.simulation = null;
        this.autoRefreshInterval = null;
        this.selectedNode = null;
        this.mockData = this.generateMockData();
        this.init();
    }

    init() {
        console.log('[Topology] init start');
        this.bindEvents();
        this.initTopology();
        this.loadTopologyData();
        console.log('[Topology] init done');
    }

    bindEvents() {
        // 控制面板事件
        document.getElementById('refreshBtn').addEventListener('click', () => this.refreshTopology());
        document.getElementById('autoRefreshBtn').addEventListener('click', () => this.toggleAutoRefresh());
        document.getElementById('timeRange').addEventListener('change', () => this.loadTopologyData());
        document.getElementById('nodeFilter').addEventListener('change', () => this.loadTopologyData());
        document.getElementById('trafficThreshold').addEventListener('change', () => this.loadTopologyData());
    }

    // 初始化拓扑图容器
    initTopology() {
        const container = document.getElementById('topologyContainer');
        this.width = container.clientWidth;
        this.height = container.clientHeight;

        this.svg = d3.select('#topologyContainer')
            .append('svg')
            .attr('id', 'topologySvg')
            .attr('width', this.width)
            .attr('height', this.height);

        // 添加缩放和平移功能
        const zoom = d3.zoom()
            .scaleExtent([0.1, 4])
            .on('zoom', (event) => {
                // 仅对主容器组应用缩放/平移，避免对子组重复叠加变换
                this.svg.select('.main-container').attr('transform', event.transform);
            });

        this.svg.call(zoom);

        // 创建主容器组
        this.svg.append('g').attr('class', 'main-container');
    }

    // 生成模拟数据
    generateMockData() {
        const nodes = [
            // 内部网络节点
            { id: 'gateway-1', name: '主网关', type: 'gateway', ip: '192.168.1.1', traffic: 15420, isInternal: true },
            { id: 'router-1', name: '核心路由器', type: 'router', ip: '192.168.1.10', traffic: 8920, isInternal: true },
            { id: 'server-1', name: 'Web服务器', type: 'server', ip: '192.168.1.100', traffic: 12450, isInternal: true },
            { id: 'server-2', name: '数据库服务器', type: 'server', ip: '192.168.1.101', traffic: 6780, isInternal: true },
            { id: 'client-1', name: '办公PC-1', type: 'internal', ip: '192.168.1.50', traffic: 2340, isInternal: true },
            { id: 'client-2', name: '办公PC-2', type: 'internal', ip: '192.168.1.51', traffic: 1890, isInternal: true },
            { id: 'client-3', name: '办公PC-3', type: 'internal', ip: '192.168.1.52', traffic: 1560, isInternal: true },
            { id: 'mobile-1', name: '移动设备', type: 'internal', ip: '192.168.1.200', traffic: 890, isInternal: true },

            // 外部网络节点
            { id: 'internet-1', name: 'Google DNS', type: 'external', ip: '8.8.8.8', traffic: 3420, isInternal: false },
            { id: 'internet-2', name: 'Cloudflare', type: 'external', ip: '1.1.1.1', traffic: 2890, isInternal: false },
            { id: 'internet-3', name: 'GitHub', type: 'external', ip: '140.82.112.3', traffic: 1560, isInternal: false },
            { id: 'internet-4', name: 'Microsoft', type: 'external', ip: '20.190.128.0', traffic: 2340, isInternal: false },
            { id: 'internet-5', name: 'AWS EC2', type: 'external', ip: '54.230.0.0', traffic: 1890, isInternal: false },
            { id: 'internet-6', name: 'CDN节点', type: 'external', ip: '104.16.0.0', traffic: 5670, isInternal: false }
        ];

        const links = [
            // 内部网络连接
            { source: 'gateway-1', target: 'router-1', traffic: 15420, type: 'internal' },
            { source: 'router-1', target: 'server-1', traffic: 8920, type: 'internal' },
            { source: 'router-1', target: 'server-2', traffic: 6780, type: 'internal' },
            { source: 'router-1', target: 'client-1', traffic: 2340, type: 'internal' },
            { source: 'router-1', target: 'client-2', traffic: 1890, type: 'internal' },
            { source: 'router-1', target: 'client-3', traffic: 1560, type: 'internal' },
            { source: 'gateway-1', target: 'mobile-1', traffic: 890, type: 'internal' },

            // 外部网络连接
            { source: 'gateway-1', target: 'internet-1', traffic: 3420, type: 'external' },
            { source: 'gateway-1', target: 'internet-2', traffic: 2890, type: 'external' },
            { source: 'client-1', target: 'internet-3', traffic: 1560, type: 'external' },
            { source: 'client-2', target: 'internet-4', traffic: 2340, type: 'external' },
            { source: 'server-1', target: 'internet-5', traffic: 1890, type: 'external' },
            { source: 'server-1', target: 'internet-6', traffic: 5670, type: 'external' },

            // 跨网络连接
            { source: 'client-3', target: 'server-1', traffic: 890, type: 'cross' },
            { source: 'client-2', target: 'server-2', traffic: 1200, type: 'cross' }
        ];

        return { nodes, links };
    }

    // 加载拓扑数据
    async loadTopologyData() {
        try {
            // 直接使用原型用的假数据渲染，不做占位与延迟
            console.log('[Topology] loading mock data...');
            const data = this.mockData;
            console.log('[Topology] data loaded:', data);
            this.renderTopology(data);
            this.updateStatistics(data);
            this.updateTrafficRanking(data);

        } catch (error) {
            console.error('加载拓扑数据失败:', error);
            Notification.error('加载拓扑数据失败');
        }
    }

    // 渲染拓扑图
    renderTopology(data) {
        console.log('[Topology] render start');
        const container = this.svg.select('.main-container');
        container.selectAll('*').remove();

        // 创建力导向图模拟
        this.simulation = d3.forceSimulation(data.nodes)
            .force('link', d3.forceLink(data.links).id(d => d.id).distance(100))
            .force('charge', d3.forceManyBody().strength(-300))
            .force('center', d3.forceCenter(this.width / 2, this.height / 2))
            .force('collision', d3.forceCollide().radius(30));

        // 绘制连接线（先隐藏，首帧后淡入，避免只看到线条）
        const linkGroup = container.append('g').attr('class', 'links').attr('opacity', 0);
        const link = linkGroup
            .selectAll('line')
            .data(data.links)
            .enter().append('line')
            .attr('class', d => {
                if (d.traffic > 5000) return 'link link-high-traffic';
                if (d.traffic > 1000) return 'link link-medium-traffic';
                return 'link link-low-traffic';
            })
            .attr('stroke-width', d => Math.max(1, Math.min(6, d.traffic / 1000)));

        // 绘制节点（与连线一起首帧后淡入）
        const nodeGroup = container.append('g').attr('class', 'nodes').attr('opacity', 0);
        const node = nodeGroup
            .selectAll('g')
            .data(data.nodes)
            .enter().append('g')
            .attr('class', 'node')
            .call(this.drag());

        // 节点圆圈
        node.append('circle')
            .attr('r', d => this.getNodeRadius(d))
            .attr('class', d => `node node-${d.type}`)
            .attr('data-id', d => d.id)
            .on('click', (event, d) => this.selectNode(d))
            .on('mouseover', (event, d) => this.showTooltip(event, d))
            .on('mouseout', () => this.hideTooltip());

        // 节点标签背景
        node.append('rect')
            .attr('class', 'node-label-bg')
            .attr('x', -30)
            .attr('y', 25)
            .attr('width', 60)
            .attr('height', 15);

        // 节点标签
        node.append('text')
            .attr('class', 'node-label')
            .attr('dy', 35)
            .text(d => d.name);

        // 流量标签
        node.append('text')
            .attr('class', 'traffic-label')
            .attr('dy', 50)
            .text(d => `${d.traffic} pkts`);

        // 更新连接线位置
        let firstFrameShown = false;
        this.simulation.on('tick', () => {
            link
                .attr('x1', d => d.source.x)
                .attr('y1', d => d.source.y)
                .attr('x2', d => d.target.x)
                .attr('y2', d => d.target.y);

            node
                .attr('transform', d => `translate(${d.x},${d.y})`);

            if (!firstFrameShown) {
                firstFrameShown = true;
                linkGroup.transition().duration(150).attr('opacity', 1);
                nodeGroup.transition().duration(150).attr('opacity', 1);
            }
        });

        // 更新计数
        document.getElementById('nodeCount').textContent = `节点: ${data.nodes.length}`;
        document.getElementById('linkCount').textContent = `连接: ${data.links.length}`;

        // 图表调试
        const canvas = document.getElementById('nodeDistChart');
        console.log('[Topology] chart canvas present:', !!canvas);
        console.log('[Topology] Chart lib present:', typeof Chart !== 'undefined');

        // 渲染精简图表（如存在）
        if (canvas && typeof Chart !== 'undefined') {
            this.renderNodeDistributionChart(data);
            console.log('[Topology] chart render invoked');
        } else {
            console.warn('[Topology] chart not rendered (missing canvas or Chart)');
        }

        console.log('[Topology] render end');
    }

    // 节点分布图（核心简化KPI）
    renderNodeDistributionChart(data) {
        const ctx = document.getElementById('nodeDistChart');
        if (!ctx || typeof Chart === 'undefined') {
            console.warn('[Topology] Chart or canvas missing');
            return;
        }

        const typeCounts = {
            gateway: data.nodes.filter(n => n.type === 'gateway').length,
            router: data.nodes.filter(n => n.type === 'router').length,
            server: data.nodes.filter(n => n.type === 'server').length,
            internal: data.nodes.filter(n => n.type === 'internal').length,
            external: data.nodes.filter(n => n.type === 'external').length
        };

        if (this.nodeDistChart) {
            try { this.nodeDistChart.destroy(); } catch (e) { console.warn('[Topology] destroy chart error', e); }
        }

        console.log('[Topology] creating chart with counts:', typeCounts);
        this.nodeDistChart = new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: ['网关', '路由器', '服务器', '内部', '外部'],
                datasets: [{
                    data: [typeCounts.gateway, typeCounts.router, typeCounts.server, typeCounts.internal, typeCounts.external],
                    backgroundColor: ['#0d6efd', '#6f42c1', '#fd7e14', '#28a745', '#ffc107'],
                    borderWidth: 0
                }]
            },
            options: {
                plugins: { legend: { display: true, position: 'bottom' } },
                maintainAspectRatio: false
            }
        });
        console.log('[Topology] chart created');
    }

    // 获取节点半径
    getNodeRadius(node) {
        const baseRadius = 15;
        const maxRadius = 25;
        const scale = Math.min(maxRadius / baseRadius, node.traffic / 5000);
        return baseRadius * (1 + scale);
    }

    // 拖拽功能
    drag() {
        return d3.drag()
            .on('start', (event, d) => {
                if (!event.active) this.simulation.alphaTarget(0.3).restart();
                d.fx = d.x;
                d.fy = d.y;
            })
            .on('drag', (event, d) => {
                d.fx = event.x;
                d.fy = event.y;
            })
            .on('end', (event, d) => {
                if (!event.active) this.simulation.alphaTarget(0);
                d.fx = null;
                d.fy = null;
            });
    }

    // 选择节点
    selectNode(node) {
        // 清除之前的选择
        this.svg.selectAll('.node-selected').classed('node-selected', false);

        // 选择当前节点
        this.svg.select(`circle[data-id="${node.id}"]`).classed('node-selected', true);

        this.selectedNode = node;
        this.showNodeDetails(node);
    }

    // 显示节点详情
    showNodeDetails(node) {
        const detailsContainer = document.getElementById('nodeDetails');
        detailsContainer.innerHTML = `
            <div class="mb-3">
                <h6 class="text-primary">${node.name}</h6>
                <small class="text-muted">${node.type.toUpperCase()} 节点</small>
            </div>
            <div class="node-detail-item">
                <span class="node-detail-label">IP地址:</span>
                <span class="node-detail-value">${node.ip}</span>
            </div>
            <div class="node-detail-item">
                <span class="node-detail-label">流量统计:</span>
                <span class="node-detail-value">${node.traffic.toLocaleString()} packets</span>
            </div>
            <div class="node-detail-item">
                <span class="node-detail-label">网络类型:</span>
                <span class="node-detail-value">${node.isInternal ? '内部网络' : '外部网络'}</span>
            </div>
            <div class="node-detail-item">
                <span class="node-detail-label">连接状态:</span>
                <span class="node-detail-value text-success">在线</span>
            </div>
            <div class="node-detail-item">
                <span class="node-detail-label">响应时间:</span>
                <span class="node-detail-value">${Math.floor(Math.random() * 50) + 10}ms</span>
            </div>
            <div class="node-detail-item">
                <span class="node-detail-label">最后活跃:</span>
                <span class="node-detail-value">${new Date().toLocaleTimeString()}</span>
            </div>
        `;
    }

    // 显示工具提示
    showTooltip(event, node) {
        const tooltip = d3.select('body').append('div')
            .attr('class', 'tooltip')
            .style('opacity', 0);

        tooltip.html(`
            <strong>${node.name}</strong><br/>
            IP: ${node.ip}<br/>
            类型: ${node.type}<br/>
            流量: ${node.traffic.toLocaleString()} packets<br/>
            网络: ${node.isInternal ? '内部' : '外部'}
        `)
        .style('left', (event.pageX + 10) + 'px')
        .style('top', (event.pageY - 10) + 'px')
        .transition()
        .duration(200)
        .style('opacity', 1);

        this.tooltip = tooltip;
    }

    // 隐藏工具提示
    hideTooltip() {
        if (this.tooltip) {
            this.tooltip.transition()
                .duration(200)
                .style('opacity', 0)
                .remove();
        }
    }

    // 更新统计信息
    updateStatistics(data) {
        const stats = {
            total: data.nodes.length,
            internal: data.nodes.filter(n => n.isInternal).length,
            external: data.nodes.filter(n => !n.isInternal).length,
            gateway: data.nodes.filter(n => n.type === 'gateway').length,
            connections: data.links.length
        };

        document.getElementById('totalNodes').textContent = stats.total;
        document.getElementById('totalConnections').textContent = stats.connections;
        document.getElementById('internalNodes').textContent = stats.internal;
        document.getElementById('externalNodes').textContent = stats.external;
        document.getElementById('gatewayNodes').textContent = stats.gateway;
    }

    // 更新流量排行
    updateTrafficRanking(data) {
        const rankingContainer = document.getElementById('trafficRanking');
        const sortedNodes = [...data.nodes].sort((a, b) => b.traffic - a.traffic).slice(0, 10);

        rankingContainer.innerHTML = sortedNodes.map((node, index) => `
            <div class="traffic-item">
                <span class="traffic-rank">${index + 1}</span>
                <span class="traffic-node">${node.name}</span>
                <span class="traffic-value">${node.traffic.toLocaleString()}</span>
            </div>
        `).join('');
    }

    // 刷新拓扑图
    refreshTopology() {
        this.loadTopologyData();
        Notification.success('拓扑图已刷新');
    }

    // 切换自动刷新
    toggleAutoRefresh() {
        const btn = document.getElementById('autoRefreshBtn');

        if (this.autoRefreshInterval) {
            clearInterval(this.autoRefreshInterval);
            this.autoRefreshInterval = null;
            btn.innerHTML = '<i class="bi bi-play-circle"></i> 自动刷新';
            btn.classList.remove('btn-success');
            btn.classList.add('btn-outline-secondary');
            Notification.info('自动刷新已停止');
        } else {
            this.autoRefreshInterval = setInterval(() => {
                this.loadTopologyData();
            }, 30000); // 30秒刷新一次

            btn.innerHTML = '<i class="bi bi-stop-circle"></i> 停止刷新';
            btn.classList.remove('btn-outline-secondary');
            btn.classList.add('btn-success');
            Notification.success('自动刷新已开启（30秒间隔）');
        }
    }

    // 清理资源
    destroy() {
        if (this.autoRefreshInterval) {
            clearInterval(this.autoRefreshInterval);
        }
        if (this.simulation) {
            this.simulation.stop();
        }
        if (this.tooltip) {
            this.tooltip.remove();
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    window.topologyPage = new TopologyPage();
});

// 页面卸载时清理资源
window.addEventListener('beforeunload', function() {
    if (window.topologyPage) {
        window.topologyPage.destroy();
    }
});
